package cn.hg.jbsa.common.web;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.jfinal.plugin.activerecord.Model;

import cn.hg.jboot.core.vo.BaseVo;
import cn.hg.jbsa.common.web.LayuiTransferData.LayuiTransferItem;

/**
 * Layui Transfer数据对象
 * <p>
 * https://gitee.com/wujiawei0926/treeselect
 * </p>
 * 
 * @author 胡高
 * @date 2021/12/20
 */
public class LayuiTransferData<T extends Model<?>> extends BaseVo implements Iterable<LayuiTransferItem<T>>{

    /**
     * 树状选择项VO
     * 
     * @author 胡高
     * @date 2021/12/20
     */
    public static class LayuiTransferItem<T extends Model<?>> extends BaseVo {

        /**
         * serialVersionUID
         */
        private static final long serialVersionUID = -5604288608883878250L;

        /**
         * 标题字段名
         */
        private String titleField;

        /**
         * 值字段名
         */
        private String valueField;

        /**
         * 项目Bean
         */
        private T bean;

        public LayuiTransferItem(T bean, String titleField, String valueField) {
            this.titleField = titleField;
            this.valueField = valueField;

            this.bean = bean;
        }

        /**
         * @return the id
         */
        public String getTitle() {
            return this.bean.getStr(this.titleField);
        }

        /**
         * @return the name
         */
        public String getValue() {
            return this.bean.getStr(this.valueField);
        }

    }

    /**
     * serialVersionUID
     */
    private static final long serialVersionUID = -3539879401089013189L;

    /**
     * 树对象数组
     */
    private List<LayuiTransferItem<T>> data;

    /**
     * 创建Transfor数据对象
     * 
     * @param titleField
     *            标题字段名
     * @param valueField
     *            值字段名
     */
    public LayuiTransferData(List<T> beanList, String titleField, String valueField) {

        // 转换项目列表为树状选择项列表
        this.data = this.convertToItemList(beanList, titleField, valueField);

    }

    private List<LayuiTransferItem<T>> convertToItemList(List<T> list, String titleField, String valueField) {
        this.data = new ArrayList<>();
        for (T bean : list) {
            this.data.add(new LayuiTransferItem<>(bean, titleField, valueField));
        }

        return this.data;
    }

    @Override
    public Iterator<LayuiTransferItem<T>> iterator() {
        return this.data.iterator();
    }
}
